﻿using System;
using System.Net;

namespace B2BCore
{
    /// <summary>
    /// Utilities Class
    /// </summary>
    public class Utilities
    {
        ///// <summary>
        ///// Get the local IP Address of the machine
        ///// </summary>
        ///// <returns>The IP Address if found, String.Empty otherwise</returns>
        //public static explicit operator string GetLocalIPAddress()
        //{
        //    IPHostEntry host;
        //    host = Dns.GetHostEntry(Dns.GetHostName());
        //    foreach (IPAddress ip in host.AddressList)
        //    {
        //        if (ip.AddressFamily.ToString() == "InterNetwork")
        //        {
        //            return ip.ToString();
        //        }
        //    }
        //    return string.Empty;
        //}

        /// <summary>
        /// Get the local IP Address of the machine
        /// </summary>
        /// <returns>The IP Address if found, IPAddress.None otherwise</returns>
        public static IPAddress GetLocalIPAddress()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return ip;
                }
            }

            return IPAddress.None;
        }

        /// <summary>
        /// Gets a variables name
        /// </summary>
        /// <typeparam name="T">The class to use</typeparam>
        /// <param name="item">The name of the variable</param>
        /// <returns></returns>
        public static string GetVariableName<T>(T item) where T : class
        {
            if (item == null)
                throw new ArgumentNullException("item", "item is null.");

            var properties = typeof(T).GetProperties();

            if (properties.Length != 1)
                throw new InvalidOperationException("Failed to get properties of item");

            return properties[0].Name;
        }
    }
}
